package com.yilin.platform.base_core.application;

import com.google.gson.reflect.TypeToken;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.entity.user.deserialize.Account;

import java.util.HashMap;
import java.util.Map;


public class UserUtil {
    private final static String PLAT_ACCOUNT_TOKEN_KEY = "PLAT_ACCOUNT_TOKEN_KEY";

    private static Map<String,Account> loginUserMap = new HashMap<>();

    //保存登录用户
    public static void saveLoginUser(String token,Account account) {
        //删除之前保存的token
        if (account.getToken()!=null) removeLoginUser(token);
        UserUtil.loginUserMap.put(token,account);
        String objectToJson = JsonUtil.objectToJson(account);
        RedisClient.getInstance().hset(PLAT_ACCOUNT_TOKEN_KEY, token,objectToJson);
    }

    //获取登录用户
    public static Account getLoginUser(String token) {
        if (StringUtil.isEmpty(token)) return null;
        if (loginUserMap.containsKey(token)) return loginUserMap.get(token);
        String objectToJson = RedisClient.getInstance().hget(PLAT_ACCOUNT_TOKEN_KEY,token);
        if (objectToJson == null) return null;
        return JsonUtil.jsonToObject(objectToJson,new TypeToken<Account>(){});
    }

    //移除API登录
    public static void removeLoginUser(String token) {
        RedisClient.getInstance().hdel(PLAT_ACCOUNT_TOKEN_KEY, token);
        loginUserMap.remove(token);
    }

}
